package com.pan.studentmaster;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;

public class BookActivity extends GridActivity {
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			_course = extras.getInt("COURSE");
			String courseName = DB.instance().getCourseName(_course);
			setTitle(courseName + " Books");
		}
	}
	
	@Override
	public Cursor getCursor() {
		return DB.instance().getBooks(_course);
	}

	@Override
	public BitmapDrawable getDrawable(Cursor cursor) {
		int bookId = cursor.getInt(cursor.getColumnIndex(DB.BOOK._ID));
		String fullpath = getFilesDir().getAbsolutePath() + "/book_" + bookId + ".png";
		try {
			Bitmap bmp = BitmapFactory.decodeFile(fullpath);
			if(bmp == null)
				throw new Exception("Decode error:" + fullpath);
			BitmapDrawable drawable = new BitmapDrawable(getResources(), bmp);
			return drawable;
		}
		catch(Exception e) {
			return null;
		}
	}
	
	@Override
	public void onItemClick(View v) {
		int bookId = v.getId();
		Intent i = new Intent().setClass(this, PageActivity.class);
		i.putExtra("BOOK", bookId);
		startActivity(i);
	}
	
	private int _course;

}
